package red.mlz.module.module.sms.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import red.mlz.module.module.sms.entity.Sms;
import red.mlz.module.module.sms.entity.SmsCrond;
import red.mlz.module.module.sms.mapper.SmsCrondMapper;
import red.mlz.module.module.sms.mapper.SmsMapper;
import red.mlz.module.utils.AliSmsUtil;
import red.mlz.module.utils.BaseUtils;

import java.util.List;

@Service
@Slf4j
public class SmsService {

    @Autowired
    private SmsMapper smsMapper;

    @Autowired
    private SmsCrondMapper smsCrondMapper;


    @Autowired(required = false)
    private AliSmsUtil aliSmsUtil;

    public String syncSend(String phone, String content) {
        String result = aliSmsUtil.sendSms(phone, content);
        Sms sms = new Sms();
        sms.setPhone(phone);
        sms.setContent(content);
        sms.setResult(result);
        sms.setCreateTime(BaseUtils.currentSeconds());
        sms.setUpdateTime(BaseUtils.currentSeconds());
        sms.setIsDeleted(0);
        smsMapper.insert(sms);
        return result;
    }

    public void asyncSend(String phone, String content) {
        SmsCrond smsCrond = new SmsCrond();
        smsCrond.setPhone(phone);
        smsCrond.setContent(content);
        smsCrond.setStatus(0);
        smsCrond.setCreateTime(BaseUtils.currentSeconds());
        smsCrond.setUpdateTime(BaseUtils.currentSeconds());
        smsCrond.setIsDeleted(0);
        smsCrondMapper.insert(smsCrond);
    }

    public List<SmsCrond> findNoSendSms() {
        return smsCrondMapper.listByStatus(0);
    }

    /**
     * 批量更新任务表
     * @param smsCrondList
     */
    public void updateSmsCrondBatch(List<SmsCrond> smsCrondList) {
        smsCrondMapper.updateBatch(smsCrondList);
    }

    public Sms crondSend(String phone, String content) {
        String result = aliSmsUtil.sendSms(phone, content);
        Sms sms = new Sms();
        sms.setPhone(phone);
        sms.setContent(content);
        sms.setResult(result);
        sms.setCreateTime(BaseUtils.currentSeconds());
        sms.setUpdateTime(BaseUtils.currentSeconds());
        sms.setIsDeleted(0);
        smsMapper.insert(sms);
        return sms;
    }

    public int insertBatch(List<Sms> smsList) {
        return smsMapper.insertBatch(smsList);
    }
}
